<template>
    <el-dialog
            :title="title"
            :visible.sync="isVisible"
            :width="width"
            :before-close="handleClose"
            :lock-scroll="true"
            :close-on-click-modal="false"
            custom-class="pub_dialog"
            @open="getData"
    >
        <VForm
                ref="vformComponents"
                :form="formData.form"
                :options="formData.options"
                :rules="formData.rules"
                :labelWidth="formData.labelWidth"
                :rowspan="rowspan"
                @changeAddress="changeAddress"
                @changeGdArea="changeGdArea"
                @toLoadMethods="toLoadMethods"
        ></VForm>

        <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure" v-if="openType!='detail'" >确 定</el-button>
    </span>
    </el-dialog>
</template>

<script>
    import { riskSourceDetail,
            riskSourceUpdate,
            riskSourceAdd } from '@/api/risk/riskSource'
    import { treeDataChild} from '@/api/risk/treeData'
    import { alarmFacilityList} from '@/api/alarm/facility'
    import VForm from "@/components/VForm/index";
    import { collectBuildingProjectList } from '@/api/build/project'
    export default {
        components: {
            VForm,
        },
        props: {
            width: {
                type: String,
                default: "70%",
            },
            title: {
                type: String,
                default: "详情",
            },
            id:{},
            openType:{
                type:String,
                default:"add"
            },
            dialogVisible: {
                type: Boolean,
                default: false
            },
            areaTreeOptions:{}
        },
        watch: {


            'width': {
                handler(newVal, oldVal) {
                    console.log('newVal===',newVal, oldVal)
                    let w = this.width.split('%')[0]
                    if(w>=60){
                        this.rowspan = 2
                    }else{
                        this.rowspan = 1
                    }
                },
                deep: true,
                immediate: true
            },
            'bClassifyOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='bclassify'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
            'sClassifyOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='sclassify'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },
            'classifyOptions':{
              handler(newVal, oldVal) {
                this.formData.options.forEach(t=>{
                  if(t.key=='classify'){
                    t.option.data = newVal
                  }
                })
              },
              deep: true,
              immediate: true
            },
            'gradeOptions':{
                handler(newVal, oldVal) {
                    this.formData.options.forEach(t=>{
                        if(t.key=='grade'){
                        t.option.data = newVal
                    }
                })
                },
                deep: true,
                immediate: true
            },

          'lifeYearOptions':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                if(t.key=='lifeYear'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },

          'levelOptions':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                if(t.key=='level'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },

          'busBclassifyOptions':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                if(t.key=='busBclassify'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },
          'busSclassifyOptions':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                if(t.key=='busSclassify'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },
          'facilityOptions':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                if(t.key=='facilityId'){
                  t.option.data = newVal
                }
              })
            },
            deep: true,
            immediate: true
          },
          'openType':{
            handler(newVal, oldVal) {
              this.formData.options.forEach(t=>{
                t.disabled =  newVal=='detail'
              })
            },
            deep: true,
            immediate: true
          },
          'buildProjectList':{
            handler(newVal, oldVal) {
              if(newVal){
                this.formData.options.forEach(t=>{
                  if(t.key == "buildingId"){
                    t.option.data = newVal
                  }
                })
              }
            },
            deep: true,
            immediate: true
          },


        },
        computed: {
            isVisible: {
                get() {
                    return this.dialogVisible
                },
                set() {
                    this.close()
                }
            }
        },
        data() {
            return {
                rowspan:1,
                dict:{},
                formData: {
                    form: {
                            flagCode:"1",
                            hazardCode:"",

                            bclassify:"",

                            sclassify:"",
                            name:"",
                            address:"",
                            memo:"",
                            classify:"",
                            grade:"",
                            unit:"",
                            unitName:"",
                            unitAddress:"",
                            affectedArea:"",
                            lifeYear:"",
                            lifeTime:"",
                            reach:"",
                            level:"",
                            disasterMemo:"",
                            receiveTime:"",
                            receiveName:"",
                            receiveContact:"",
                            lon:"",
                            lat:"",
                            provinceCode:"",
                            cityCode:"",
                            countyCode:"",
                            areaCode:"",
                            delFlag:"",
                            mapData:null,
                            busBclassify:'',
                            busSclassify:'',
                            facilityId:'',
                            facilityName:'',

                        },
                    options: [


                              {
                                title: "所属工地",
                                key: "buildingId",
                                type: "select",
                                multiple: false,
                                disabled: false,
                                option: {
                                  data: this.buildProjectList,
                                  props: {
                                    key: "id", // 指定key对应data的字段
                                    label: "projectName", // 指定label对应data的字段
                                    value: "id", // 指定value对应data的字段
                                  },
                                },
                              },
                                   {
                                       title: "危险源代码",
                                       key: "hazardCode",
                                       type: "text",
                                   },
                                {
                                    title: "危险源大类",
                                    key: "bclassify",
                                    type: "select",
                                    multiple:false,
                                    event:'changeBclassify',
                                    option: {
                                        data: this.bClassifyOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "name", // 指定value对应data的字段
                                        },
                                    },
                                },
                                {
                                    title: "危险源细类",
                                    key: "sclassify",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                        data: this.sClassifyOptions,
                                        props: {
                                            key: "id", // 指定key对应data的字段
                                            label: "label", // 指定label对应data的字段
                                            value: "name", // 指定value对应data的字段
                                        },
                                    },
                                },
                                   {
                                       title: "危险源名称",
                                       key: "name",
                                       type: "text",
                                   },
                                    {
                                      title: "危险源密级",
                                      key: "classify",
                                      type: "select",
                                      multiple:false,
                                      option: {
                                        data: this.classifyOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "value", // 指定value对应data的字段
                                        },
                                      },
                                    },
                                    {
                                      title: "危险源等级",
                                      key: "grade",
                                      type: "select",
                                      multiple:false,
                                      option: {
                                        data: this.gradeOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "value", // 指定value对应data的字段
                                        },
                                      },
                                    },

                                    {
                                      title: "地址",
                                      type:'mapPosition',
                                      key:'mapData',
                                    },


                                   {
                                       title: "危险源描述",
                                       key: "memo",
                                       type: "textarea",
                                       columnWidth: 'w100max',
                                   },






                                   {
                                       title: "主管单位",
                                       key: "unit",
                                       type: "text",
                                   },
                                   {
                                       title: "单位负责人",
                                       key: "unitName",
                                       type: "text",
                                   },
                                   {
                                       title: "单位地址",
                                       key: "unitAddress",
                                       type: "text",
                                   },
                                   {
                                       title: "影响面积(km2)",
                                       key: "affectedArea",
                                       type: "number-input",
                                   },


                                  {
                                    title: "使用年限",
                                    key: "lifeYear",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                      data: this.lifeYearOptions,
                                      props: {
                                        key: "id", // 指定key对应data的字段
                                        label: "label", // 指定label对应data的字段
                                        value: "value", // 指定value对应data的字段
                                      },
                                    },
                                  },


                                   {
                                       title: "使用时间",
                                       key: "lifeTime",
                                       type: "date",
                                   },
                                   {
                                       title: "影响范围",
                                       key: "reach",
                                       type: "text",
                                   },


                                  {
                                    title: "危险级别",
                                    key: "level",
                                    type: "select",
                                    multiple:false,
                                    option: {
                                      data: this.levelOptions,
                                      props: {
                                        key: "id", // 指定key对应data的字段
                                        label: "label", // 指定label对应data的字段
                                        value: "value", // 指定value对应data的字段
                                      },
                                    },
                                  },
                                   {
                                       title: "可能灾害形式",
                                       key: "disasterMemo",
                                       type: "text",
                                   },
                                   {
                                       title: "数据收集时间",
                                       key: "receiveTime",
                                       type: "date",
                                   },
                                   {
                                       title: "数据收集人",
                                       key: "receiveName",
                                       type: "text",
                                   },
                                   {
                                       title: "收集人电话",
                                       key: "receiveContact",
                                       type: "text",
                                   },

                                    {
                                      title: "业务专题大类",
                                      key: "busBclassify",
                                      type: "select",
                                      multiple:false,
                                      event:'changeBusBclassify',
                                      option: {
                                        data: this.busBclassifyOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "name", // 指定value对应data的字段
                                        },
                                      },
                                    },
                                    {
                                      title: "业务专题细类",
                                      key: "busSclassify",
                                      type: "select",
                                      multiple:false,
                                      event:'changeFacilityId',
                                      option: {
                                        data: this.busSclassifyOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "name", // 指定value对应data的字段
                                        },
                                      },
                                    },
                                    {
                                      title: "工地设施名称",
                                      key: "facilityId",
                                      type: "select",
                                      multiple:false,
                                      event:'changeFacilityName',
                                      option: {
                                        data: this.facilityOptions,
                                        props: {
                                          key: "id", // 指定key对应data的字段
                                          label: "label", // 指定label对应data的字段
                                          value: "name", // 指定value对应data的字段
                                        },
                                      },
                                    },



                    ],
                    rules: {
                        flagCode :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],
                        hazardCode :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        bclassify :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        sclassify :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        name :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:64, message: '长度最大为64个字符', trigger: 'blur'}
                        ],
                        address :[

                          {max:200, message: '长度最大为200个字符', trigger: 'blur'}
                        ],
                        memo :[
                          {max:1024, message: '长度最大为1024个字符', trigger: 'blur'}
                        ],
                        classify :[
                          { required: true, message: '请选择', trigger: 'blur' }
                        ],
                        grade :[
                          { required: true, message: '请选择', trigger: 'blur' },
                        ],
                        unit :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        unitName :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:32, message: '长度最大为32个字符', trigger: 'blur'}
                        ],
                        unitAddress :[
                          { required: true, message: '请输入', trigger: 'blur' },
                          {max:200, message: '长度最大为200个字符', trigger: 'blur'}
                        ],
                        affectedArea :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],
                        lifeYear :[
                          { required: true, message: '请输入', trigger: 'blur' }
                        ],
                        lifeTime :[
                          { required: true, message: '请输入', trigger: 'blur' }
                        ],
                        reach :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],
                        level :[
                        ],
                        disasterMemo :[
                          {max:128, message: '长度最大为128个字符', trigger: 'blur'}
                        ],
                        receiveTime :[
                        ],
                        receiveName :[
                          {max:50, message: '长度最大为50个字符', trigger: 'blur'}
                        ],
                        receiveContact :[
                          {max:20, message: '长度最大为20个字符', trigger: 'blur'}
                        ],
                        lon :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        lat :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                        provinceCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        cityCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        countyCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        areaCode :[
                          {max:12, message: '长度最大为12个字符', trigger: 'blur'}
                        ],
                        updateTime :[
                        ],
                        updateBy :[
                          {max:36, message: '长度最大为36个字符', trigger: 'blur'}
                        ],
                    },
                    labelWidth: "120px",
                },
            // 字典
                bClassifyOptions:[],
                sClassifyOptions:[],
                classifyOptions:[],
                gradeOptions:[],
                lifeYearOptions:[],
                levelOptions:[],
                busBclassifyOptions:[],
                busSclassifyOptions:[],
                facilityOptions:[],
                buildProjectList:[]
            };
        },
        methods: {

          toLoadMethods(methods){
            this[methods]();
          },
          changeFacilityName(){
            var label = this.facilityOptions.find(t=>t.name==this.formData.form.facilityId).label;
            this.formData.form.facilityName=label;

          },
          changeBclassify(){
            // this.formData.form.sclassify='';
            // this.sClassifyOptions=[]
            // this.sendBclassifyData();
          },

          async sendBclassifyData(){
            let queryData ={}
            queryData.name='riskBClassify';
            queryData.code =this.formData.form.bclassify;
            let res =await treeDataChild(queryData);
            if(res.code==200) {
              let that = this
              res.data.forEach(function (item,index){
                var one ={}
                one.label= item.label;
                one.name=item.code;
                that.sClassifyOptions.push(one);
              })
            }
          },


          changeBusBclassify(){

            this.formData.form.busSclassify='';
            this.busSclassifyOptions=[];
            this.formData.form.facilityId='';
            this.formData.form.facilityName='';
            this.facilityOptions=[]
            this.sendBusBclassifyData();
          },

          async sendBusBclassifyData(){
            let queryData ={}
            queryData.name='hazardBClassify';
            queryData.code =this.formData.form.busBclassify;
            let res =await treeDataChild(queryData);
            if(res.code==200) {
              let that = this
              res.data.forEach(function (item,index){

                if(item.modeType){
                  var one ={}
                  one.label= item.label;
                  one.name=item.modeType;

                  that.busSclassifyOptions.push(one);
                }

              })


            }


          },

          changeFacilityId(){

            this.formData.form.facilityId='';
            this.formData.form.facilityName='';
            this.facilityOptions=[]
            this.sendFacilityData();
          },

          async sendFacilityData(){
            let queryData ={}
            queryData.modeType="ALARM_"+this.formData.form.busSclassify;
            queryData.areaCodeFormat = this.$store.state.account.user.deptIds;
            let res =await alarmFacilityList(queryData);
            if(res.code==200) {
              let that = this
              res.data.forEach(function (item,index){
                var one ={}
                one.label=item.name ;
                one.name=item.id;
                that.facilityOptions.push(one);
              })

            }
          },

          getCountySubIndex(cityCode){
            // 中山、东莞截取10位
            let filterList = ['442000000000','441900000000']
            if(filterList.findIndex(t=>t==cityCode)>-1){
              return 10;
            }
            return 6;
          },
          positionSubmitFormat(){

            let mapData = this.formData.form.mapData
            if(mapData){
              this.formData.form.lon = mapData.gpsX
              this.formData.form.lat = mapData.gpsY
              this.formData.form.address = mapData.address
              this.formData.form.areaCode = mapData.towncode
              if(mapData.towncode){
                this.formData.form.provinceCode = mapData.towncode.substr(0,2).padEnd(12,'0')
                this.formData.form.cityCode = mapData.towncode.substr(0,4).padEnd(12,'0')
                let subIndex = this.getCountySubIndex(this.formData.form.cityCode)
                this.formData.form.countyCode = mapData.towncode.substr(0,subIndex).padEnd(12,'0')
              }
            }
          },
          positionLoadFormat(){
              let form = this.formData.form
              let mapData = {}
              mapData.address = form.address

                mapData.gpsX = parseFloat(form.lon)
                mapData.gpsY = parseFloat(form.lat)

              mapData.towncode = form.areaCode
              this.formData.form.mapData = mapData
              console.log("mpap",mapData)
            },


            submitFormat(){
            },
            loadFormat(){
            },
            getCheckBoxData(value,option,type){
                if(type=="submit"){
                    if(value.length==0){
                        return null
                    }
                    let temp = [];
                    value.forEach(t=>{
                        let item = option.find(x=> x.label == t)
                    if(item!=undefined){
                        temp.push(item.value)
                    }
                })
                    return temp.join(",")
                }else {
                    if(!value){
                        return []
                    }else {
                        let data = value.split(",")
                        let temp = []
                        data.forEach(t=>{
                            let item = option.find(x=> x.value == t)
                        if(item!=undefined){
                            temp.push(item.label)
                        }
                    })
                        return temp
                    }
                }
            },
            sure(){
                console.log('sure===',this.formData.form)
                this.$refs.vformComponents.$refs.form.validate().then(res=>{
                    this.submitFormat()
                    if(this.formData.form.areaCode){
                      let temp  = this.formData.form.areaCode
                      this.formData.form.provinceCode = temp[0]
                      this.formData.form.cityCode = temp[1]
                      this.formData.form.countyCode = temp[2]
                      this.formData.form.areaCode = temp[2]
                    }
                    this.positionSubmitFormat()
                    if(this.openType == "add"){
                        this.add()
                    }else{
                        this.update()
                    }
                })
            },
            add(){
                this.formData.form.id = null
                this.formData.form.delFlag=0;
                riskSourceAdd(this.formData.form).then(res=>{
                    if(res.code==200){
                    this.$message({
                        message: this.$t('tips.createSuccess'),
                        type: 'success'
                    })
                    this.closeSuccess()
                    }else{
                    this.$message({
                        message: this.$t('tips.systemException'),
                        type: 'error'
                    })
                    }
                })
            },
            update(){
                   riskSourceUpdate(this.formData.form).then(res=>{
                        if(res.code==200){
                        this.$message({
                             message: this.$t('tips.updateSuccess'),
                            type: 'success'
                        })
                        this.closeSuccess()
                      }else{
                        this.$message({
                            message: this.$t('tips.systemException'),
                            type: 'error'
                        })
                     }
                })
            },
            cancel(){
                this.close()
            },
            handleClose(done) {
                done()
                this.close()
            },
            closeSuccess(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.busSclassifyOptions=[];
                this.facilityOptions=[],
                  this.formData.form.facilityName="";
                this.$emit('success')
            },
            close(){
                this.$refs.vformComponents.$refs.form.resetFields();
                this.$refs.vformComponents.$refs.mapPosition[0].reloadMap();
                this.busSclassifyOptions=[];
                this.facilityOptions=[]
                this.formData.form.facilityName="";
                this.$emit('close')
            },
            getBuildProjectList(){
              collectBuildingProjectList().then(res=>{
                if(res.code==200){
                  this.buildProjectList = res.data
                }
              })
            },
            getData(){
              // 获取字典值
              this.bClassifyOptions = []
              this.$commonJs.filterDataDict("riskBClassify",this.bClassifyOptions )

              this.sClassifyOptions=[]
              this.$commonJs.filterDataDict("riskSClassify",this.sClassifyOptions )

              this.gradeOptions=[]
              this.$commonJs.filterDataDict("riskGrade",this.gradeOptions )

              this.classifyOptions=[]
              this.$commonJs.filterDataDict("riskClassify",this.classifyOptions )

              this.lifeYearOptions=[]
              this.$commonJs.filterDataDict("riskLifeYear",this.lifeYearOptions )

              this.levelOptions=[]
              this.$commonJs.filterDataDict("riskLevel",this.levelOptions )


              // 获取字典值
              this.busBclassifyOptions = []
              this.$commonJs.filterDataDict("hazardBClassify",this.busBclassifyOptions )

              //获取工地
              this.getBuildProjectList()

                if(this.openType!="add"){
                    riskSourceDetail(this.id).then(res=>{
                        if(res.code==200){
                            this.formData.form = res.data
                            this.sendBusBclassifyData()
                            this.sendFacilityData()
                            this.loadFormat()
                            this.positionLoadFormat()
                         }else{
                            this.$message({
                                message: this.$t('tips.systemException'),
                                type: 'error'
                            })
                        }
                    })
                }
            },
            changeAddress(data){
              // console.log(data)
              this.formData.form.mapData = data
              this.formData.form.areaCode = data.areaCode
            },
            changeGdArea(data){
              console.log(data)
            },
        },
    };
</script>

<style lang="scss" scoped>

</style>
